<template>
  <div class="main-box">
    <div class="card content-box w-full">
      <TableContainer :is-page="false">
        <template #searchCard>
          <SearchFrom :search-event="handleSearchEvent" />
        </template>
        <template #btnLeft>
          <el-button v-auth="['menu:add:btn']" type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增
          </el-button>
          <el-button type="default" @click="openOrCloseMenuTree">
            <el-icon>
              <Sort />
            </el-icon>
            {{ activeTreeStatus ? "收起" : "展开" }}
          </el-button>
        </template>
        <el-table
          v-bind="$attrs"
          :data="[...tableData]"
          row-key="id"
          :height="gridOptions.height"
          :show-overflow-tooltip="gridOptions.showOverflow"
        >
          <template #empty>
            <span>暂无数据</span>
          </template>
          <el-table-column v-for="item in gridOptions.columns" v-bind="{ ...item, ...$attrs }" :key="item.prop">
            <template #default="{ row }">
              <span v-if="item.slots === 'name'" class="flex items-center" @click="handleEdit(row)">
                <IconView :model-value="row.icon ? row.icon : 'ele-Tickets'"></IconView>
                <el-link type="primary" class="ml-1" :underline="false">{{ row.name }}</el-link>
              </span>
              <el-tag v-if="item.slots === 'menuType'" :type="row.menuType == 2 ? 'success' : 'primary'">
                {{ menuTypeDict[row.menuType] }}
              </el-tag>
              <el-tag v-if="item.slots === 'permission' && row.permission" type="primary" v-copy="row.permission">
                {{ row.permission }}
              </el-tag>
              <div class="w-full flex items-center justify-center" v-if="item.slots === 'controls'">
                <el-button v-auth="['menu:add:btn']" link type="primary" @click="handleAdd($event, row)" v-if="row.menuType != 2">
                  <el-icon>
                    <CirclePlus />
                  </el-icon>
                  新增下级
                </el-button>
                <el-button v-auth="['menu:edit:btn']" link type="primary" @click="handleEdit(row)">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  编辑
                </el-button>
                <el-button v-auth="['menu:delete:btn']" link type="danger" @click="handleDelete(row)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </TableContainer>
    </div>
    <MenuAdd ref="menuAddRef" @close="handleClose"></MenuAdd>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { deleteMenu, getMenuDetail, getMenuTreeList } from "@/api/modules/menu";
import { useComponentRef } from "@/hooks/useComponentRef";
import SearchFrom from "./components/SearchFrom.vue";
import { useTableConfig } from "@/hooks/useTable";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import TableContainer from "@/components/TableContainer/index.vue";
import { usePagination } from "alova/client";
import { Menu } from "@/typings/global";

const MenuAdd = defineAsyncComponent(() => import("./components/add.vue"));
const menuAddRef = useComponentRef(MenuAdd);

const menuTypeDict = reactive({
  0: "目录",
  1: "菜单",
  2: "按钮"
});

let searchForm = reactive<Menu.IMenuParams>({
  name: ""
});
const activeTreeStatus = ref(false);

const { gridOptions } = useTableConfig({
  columns: [
    { prop: "id", label: "ID", align: "left", width: 100 },
    { prop: "name", label: "菜单名称", align: "left", slots: "name" },
    { prop: "path", label: "菜单路径", align: "left" },
    { prop: "permission", label: "权限标识", align: "left", slots: "permission", width: 200 },
    { prop: "menuType", label: "类型", align: "left", slots: "menuType" },
    { prop: "sortOrder", label: "排序", align: "left" },
    { prop: "createTime", label: "创建时间", align: "left" }
  ]
});

const { data: tableData, send } = usePagination(() => getMenuTreeList(searchForm.name), {
  force: true,
  data: response => response.data ?? []
});

const handleAdd = (evt: MouseEvent, row?: Menu.IMenu) => {
  menuAddRef.value?.openDialog("add", { parentId: row?.id || -1 });
};

const handleEdit = async (row: Menu.MenuOptions) => {
  try {
    const { BUTTONS } = useAuthButtons();
    if (!BUTTONS("menu:edit:btn")) return;
    if (!row.id) return;
    const { data } = await getMenuDetail(row.id);
    console.log(data);
    menuAddRef.value?.openDialog("edit", data);
  } catch (e) {}
};

const handleDelete = async (row: Menu.MenuOptions) => {
  try {
    if (!row.id) return;
    await deleteMenu(row.id);
    ElMessage.success("删除成功");
    await send();
  } catch (e) {}
};

const handleSearchEvent = (form: Menu.IMenuParams) => {
  searchForm = form;
  send();
};

const openOrCloseMenuTree = () => {
  // const $grid = grid.value;
  // if ($grid) {
  //   activeTreeStatus.value = !activeTreeStatus.value;
  //   $grid.setAllTreeExpand(activeTreeStatus.value);
  // }
};
const handleClose = () => {
  send();
};
</script>

<style scoped lang="scss">
:deep(.el-link) {
  --el-link-font-weight: 400;
}
</style>
